package com.jufanshare.myblog.common.util;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
 * 作用：发起一个http请求，使用okhttp请求，包含GET和POST请求
 * 作者：Tiddler
 * 时间：2018-08-2018/8/3 16：00
 * 类名：CreateRequest
 **/
public class CreateRequest {
    private final static Logger log= LogManager.getLogger(CreateRequest.class);

    /**
     * GET请求一个地址，并且获取那个地址返回的页面文本
     * @param reqUrl
     * @return
     */
    public static String doGET(String reqUrl,String host){
        String responseContext = null;
        OkHttpClient client = new OkHttpClient();
        //加入一些请求头信息，可以针对大多数做了防爬虫的网页
        Request request = new Request.Builder().url(reqUrl)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36")
                .addHeader("Cookie", "__DAYU_PP=RM6n2mRjmN72jmMj6EEA2a6864d9cc44; _user_behavior_=29bcd06e-a622-4d37-b695-49184ee40871; oscid=18%2B24OHTNObWgBnHCgtLk300eOsXufOKvWH7QK2Ay9CElLuXYaxAILHsw%2BFaKg1sSis1yBGy7tIqZvBCa6l2GXK7Ft8x8NKATm2Iv45JfYRCEpskLpjxpFOZFGHfR3E%2Bqrobjhd%2B3XuDy3ECR9VTzQ2rz4u0Uy1sg97o1G38qCs%3D; bad_id8387c580-a888-11e5-bc38-bb63a4ea0854=1e27ba51-469d-11e8-927f-c364363c7a3c; banner_osc_scr0710=1; aliyungf_tc=AQAAADP46lC7EwoA1NhXZUbBIrn2AIIq; Hm_lvt_a411c4d1664dd70048ee98afe7b28f0b=1531212092,1531352328,1531378414; Hm_lpvt_a411c4d1664dd70048ee98afe7b28f0b=1531384849")
                .get()
                .build();
        try {
            Response response = client.newCall(request).execute();
//            log.debug(response.headers().size());
//            for(int i=0;i<response.headers().size();i++){
//                log.debug(response.headers().name(i)+"\t"+response.headers().get(response.headers().name(i)));
//            }
            byte[] bytes = response.body().bytes();
            String encoding = GetByteEncode.getEncoding(bytes);//编码判断
            System.out.println("字符编码是："+encoding);
            if(encoding.indexOf("GB")>=0){//由于GBK编码有多种，此处这样判断即可
                responseContext = new String(bytes,"gbk");
            }
            if("UTF-8".equals(encoding)){
                responseContext = new String(bytes,"utf-8");
            }
        } catch (Exception e) {
            log.info("发起网络请求出错："+reqUrl);
            log.debug(e.getMessage());
//            e.printStackTrace();
        }
        return responseContext;
    }

}
